package com.atguigu.threadtest;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ClassName: ReentrantReadWriteLockDemo
 * Package: com.atguigu
 * Description:
 *
 * @author: fu-wang
 * @create: 2024/10/28 19:34
 * version: 1.0
 */
public class ReentrantReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        //开启五个写入线程
        for (int i = 0; i < 5; i++) {
            String num = String.valueOf(i);
            new Thread(()->{
                myCache.put(num,num);
                        },"thread put").start();
        }
        //开启五个读出线程
        for (int i = 0; i < 5; i++) {
            String num = String.valueOf(i);
            new Thread(()->{
                myCache.get(num);
                        },"thread get").start();
        }
    }
}
class MyCache{
    //加入读写锁
    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private Map<String,String> map = new HashMap<>();
    //写
    public void put(String key,String value){
        //加入写锁
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"开始写入...");
            Thread.sleep(300);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //释放写锁
            readWriteLock.writeLock().unlock();
        }
    }
    //读
    public void get(String key){
        //加入读锁
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"开始读出...");
            Thread.sleep(300);
            String str = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读出完成"+str);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //释放读锁
            readWriteLock.readLock().unlock();
        }
    }
}